//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由(常量路由)
import { constantRoute, asnycRoute, anyRoute } from '@/router/routes'

//引入深拷贝方法
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'
//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组(路由)
      username: '',
      avatar: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      // 模拟登录逻辑
      if (data.username === 'admin' && data.password === '111111') {
        // 生成模拟token
        const token = 'mock-token-' + new Date().getTime()
        //pinia仓库存储一下token
        this.token = token
        //本地存储持久化存储一份
        SET_TOKEN(token)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error('用户名或密码错误'))
      }
    },
    //获取用户信息方法
    async userInfo() {
      // 模拟获取用户信息
      // 检查是否有token
      if (this.token) {
        // 模拟用户信息
        this.username = 'admin'
        this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        // 模拟按钮权限
        this.buttons = ['btn.User', 'btn.Role', 'btn.Permission']
        // 模拟路由权限
        const routes = ['home', 'user', 'role', 'permission']
        //计算当前用户需要展示的异步路由
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asnycRoute),
          routes,
        )
        //菜单需要的数据整理完毕
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        [...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error('未登录'))
      }
    },
    //退出登录
    async userLogout() {
      // 模拟退出登录
      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
      return 'ok'
    },
  },
  getters: {},
})
//对外暴露获取小仓库方法
export default useUserStore